﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Collections;
using Microsoft.Win32;
using System.Data;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Net;
using System.Management.Automation;
using System.Security;
using System.Management.Automation.Runspaces;
using Microsoft.SharePoint;
using System.Threading;


namespace ExchangeServerWebPart
{
    public static class ExchangeServerHelper
    {
        private const string EVENT_LOG_SOURCE_NAME = "Connecting with Exchange Server 2010";
        private const string strLogType = "Application"; //type of the log
        static string errorMessage = "";
        public static bool IS_ERROR = false;
        private const string EXCHANGE_NAME = "ECMXCH0801.ecm.int";
        private const string EXCHANGE_USERNAME = "ECM\\SKVExchSRVAccount";
        private const string EXCHANGE_PASSWORD = "pass@word1";




        public static bool ConnectWithExchangeServer()
        {

            bool isOperationSuccessfull = false;
            PSCredential credential = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                     delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                 System.Security.Cryptography.X509Certificates.X509Chain chain,
                                 System.Net.Security.SslPolicyErrors sslPolicyErrors)
                     {
                         return true; // **** Always accept
                     };

                    if (EXCHANGE_USERNAME.Length > 0 &&
                        EXCHANGE_PASSWORD.Length > 0)
                    {

                        string insecurePassword = EXCHANGE_PASSWORD;
                        SecureString securePassword = new SecureString();
                        foreach (char passChar in insecurePassword.ToCharArray())
                        {
                            securePassword.AppendChar(passChar);
                        }
                        credential = new PSCredential(EXCHANGE_USERNAME, securePassword);
                    }


                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://"
                        + EXCHANGE_NAME
                        + "/powershell"),
                        "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                    if (connectionInfo != null)
                    {
                        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                        connectionInfo.SkipCACheck = true;
                        connectionInfo.SkipCNCheck = true;
                        LogSuccess("Connection information is successfully found:" + connectionInfo.ConnectionUri.ToString());
                        isOperationSuccessfull = true;
                    }
                    else
                    {
                        throw new Exception("Unable to make the connection, please check username or password");
                    }


                }
                catch (Exception e)
                {
                    isOperationSuccessfull = false;
                    LogError(e.ToString());
                }
            });
            return isOperationSuccessfull;


        }
        public static bool CreateContact(string Name, string FirstName, string LastName, string ExternalEmail, string OrginizationalUnit)
        {

            bool isOperationSuccessfull = false;
            PSCredential credential = null;

            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                 delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                             System.Security.Cryptography.X509Certificates.X509Chain chain,
                             System.Net.Security.SslPolicyErrors sslPolicyErrors)
                 {
                     return true; // **** Always accept
                 };

                if (EXCHANGE_USERNAME.Length > 0 &&
                    EXCHANGE_PASSWORD.Length > 0)
                {

                    string insecurePassword = EXCHANGE_PASSWORD;
                    SecureString securePassword = new SecureString();
                    foreach (char passChar in insecurePassword.ToCharArray())
                    {
                        securePassword.AppendChar(passChar);
                    }
                    credential = new PSCredential(EXCHANGE_USERNAME, securePassword);
                }


                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://"
                    + EXCHANGE_NAME
                    + "/powershell"),
                    "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                if (connectionInfo != null)
                {
                    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
                    connectionInfo.SkipCACheck = true;
                    connectionInfo.SkipCNCheck = true;
                    LogSuccess("Connection information is successfully found:" + connectionInfo.ConnectionUri.ToString());

                }
                else
                {
                    throw new Exception("Unable to make the connection, please check username or password");
                }


                Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                PowerShell powershell = PowerShell.Create();
                PSCommand command = new PSCommand();
                ICollection<System.Management.Automation.PSObject> results;
                //set the external email properties 
                ExternalEmail = string.Format("{0}@corp.com", ExternalEmail);



                //New-MailContact
                try
                {

                    runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                    powershell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddCommand("New-MailContact");
                    command.AddParameter("Name", Name);
                    command.AddParameter("Alias", Name);
                    if (!String.IsNullOrEmpty(FirstName))
                        command.AddParameter("FirstName", FirstName);
                    if (!String.IsNullOrEmpty(LastName))
                        command.AddParameter("LastName", LastName);
                    if (!String.IsNullOrEmpty(FirstName))
                        command.AddParameter("DisplayName", FirstName);
                    if (!String.IsNullOrEmpty(OrginizationalUnit))
                        command.AddParameter("OrganizationalUnit", OrginizationalUnit);
                    if (!String.IsNullOrEmpty(ExternalEmail))
                        command.AddParameter("ExternalEmailAddress", ExternalEmail);

                    //command.AddParameter("EmailAddressPolicyEnabled", false);
                    if (!String.IsNullOrEmpty(ExternalEmail))
                    {
                        command.AddParameter("PrimarySmtpAddress", ExternalEmail);
                    }
                    command.AddParameter("Confirm", false);
                    //command.AddParameter("Force", true);
                    powershell.Commands = command;

                    // open the remote runspace
                    runspace.Open();
                    // associate the runspace with powershell
                    powershell.Runspace = runspace;
                    // invoke the powershell to obtain the results
                    results = powershell.Invoke();
                    isOperationSuccessfull = true;
                }
                catch (Exception ex)
                {
                    isOperationSuccessfull = false;
                    LogError(ex.ToString());
                    throw new Exception("Error executing script at Exchange Server: " + ex.ToString());
                }
                finally
                {

                    runspace.Dispose();
                    runspace = null;
                    // Finally dispose the powershell and set all variables to null to free
                    // up any resources.
                    powershell.Dispose();
                    powershell = null;
                    if (isOperationSuccessfull)
                        LogSuccess("Successfully created Mail Contact");
                }


            }
            catch (Exception e)
            {
                isOperationSuccessfull = false;
                LogError(e.ToString());
            }

            return isOperationSuccessfull;

        }

        #region Log the Error, Information and Warning to the Windows Event Viewer
        internal static void LogWarning(string msg)
        {
            try
            {
                EventLog eventLog;
                if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
                }
                if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    eventLog = new EventLog("Application");
                    eventLog.Source = EVENT_LOG_SOURCE_NAME;
                    StringBuilder sb = new StringBuilder(100);
                    sb.Append("Samabetsrum : ");
                    sb.Append("\r\n");
                    sb.Append(msg);
                    eventLog.WriteEntry(msg, EventLogEntryType.Warning, 0);
                }
            }
            catch
            {

            }
        }
        internal static void LogError(string error)
        {
            try
            {
                EventLog eventLog;
                if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
                }
                if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    eventLog = new EventLog("Application");
                    eventLog.Source = EVENT_LOG_SOURCE_NAME;
                    StringBuilder sb = new StringBuilder(100);
                    sb.Append("Samabetsrum: ");
                    sb.Append("\r\n");
                    sb.Append(error);
                    eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error, 0);
                }
            }
            catch
            {
            }
        }
        internal static void LogSuccess(string information)
        {
            try
            {
                EventLog eventLog;
                if (!EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    EventLog.CreateEventSource(EVENT_LOG_SOURCE_NAME, strLogType);
                }
                if (EventLog.SourceExists(EVENT_LOG_SOURCE_NAME))
                {
                    eventLog = new EventLog("Application");
                    eventLog.Source = EVENT_LOG_SOURCE_NAME;
                    StringBuilder sb = new StringBuilder(100);
                    sb.Append("Samabetsrum: ");
                    sb.Append("\r\n");
                    sb.Append(information);
                    eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information, 0);

                }
            }
            catch
            {

            }
        }

        #endregion

    }
}
